import axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'
import router from '../router';

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    name:'',
    cart:[]
  },
  mutations: {
    setName(state,name){
      state.name = name
      axios(`/user/cart?userName=${name}`).then(res=>{
        if(res.data[0].cart){
          state.cart = res.data[0].cart
        }else{
          state.cart = []
        }
      })
    },
    addCart(state,commodity){
      var cart = state.cart
      var res = cart.some(item=>item._id == commodity._id )
      var userName = state.name
      if(userName){
        if(cart.length == 0){
          userName = state.name
          axios.post('/user/addcart',{userName,commodity}).then(res=>{
            alert(res.data.msg)
          })
          cart.push(commodity)
        }else if(!res){
          userName = state.name
          axios.post('/user/addcart',{userName,commodity}).then(res=>{
            alert(res.data.msg)
          })
          cart.push(commodity)
        }else{
          alert('购物车中已经存在该商品！')
        }
        state.cart = cart
      }else{
        alert('请先登录！')
        router.push('/login')
      }
    }
  },
  actions: {
  },
  modules: {
  }
})
